/* eslint-disable @typescript-eslint/no-shadow */
/* eslint-disable eqeqeq */
/* eslint-disable @babel/no-unused-expressions */
/* eslint-disable camelcase */
// 债券维护
import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, TreeSelect } from 'antd';
import { TableC, AdvancedSearch, PrimaryC, DATA_ENTRY, ModalC, FormGroup, codeType, ExportC, PrimaryGhostC } from '../../../../comps';
import config from '../../../../comps/business/tradingMarket/config';
import myStyle from '../index.less';
// 组件
import RightInfo from '../shareComp/rightInfo';
import TipsInfo from '../shareComp/tipInfo';
import IssuerModal from './issuerModal';
import InfoModal from './infoModal';
import { findValueByCode } from '../../../../utils/utils';

@Form.create()
class BondInfo extends React.Component {
  constructor() {
    super();
    this.state = {
      id: undefined, // 编辑id
      tradingCode: '',
      searchObj: {}, // 查询的条件
      currentPage: 1, // 页码
      numInPage: 10, // 一页展示数量
      total: 0, // 表格总数
      columns: [
        {
          title: '证券代码',
          dataIndex: 'tradingCode',
          key: 'tradingCode',
        },
        {
          title: '证券名称',
          dataIndex: 'secuabbr',
          key: 'secuabbr',
        },
        {
          title: '交易市场',
          dataIndex: 'securityExchange',
          key: 'securityExchange',
        },
        {
          title: '债券类型',
          dataIndex: 'bondType',
          key: 'bondType',
        },
        {
          title: '债项评级',
          dataIndex: 'bondRating',
          key: 'bondRating',
        },
        {
          title: '补充工具',
          dataIndex: 'supplementaryTool',
          key: 'supplementaryTool',
        },
        {
          title: '租户',
          dataIndex: 'tenant',
          key: 'tenant',
        },
        {
          title: '发行机构所属行业',
          dataIndex: 'issuerIndustry',
          key: 'issuerIndustry',
        },
        {
          title: '发行机构类型(按规模划分)',
          dataIndex: 'issuerScale',
          key: 'issuerScale',
        },
        {
          title: '发行人',
          dataIndex: 'issuer',
          key: 'issuer',
        },
        {
          title: '来源',
          key: 'originType',
        },
      ], // 表格头
      dataSource: [], // 表格数据
      isReset: false, // 是否点击重置
      count: undefined, // 与资讯不一致
      selectedRowKeys: [], // 表格checkbox选择
      selectedRows: [], // 表格checkbox选择
      isBatchConfirmation: false, // 批量确认按钮置灰
      pageType: '', // 编辑/新增字段
      bondTypeList: [], // 债券类型下拉列表
      flag: '1', // 1全部 2不一致 3无评级
      addedThisMonth: 0, // 本月新增条数
      isHistory: false, // 是否是历史日期
      noRateCount: 0, // 无评级条数
      holdDataList: [], // 持仓日期下拉
      latestholdDate: '', // 最新的持仓日期
      filteredInfo: null, // 筛选信息 受控
      issuerVisible: false, // 同发行人校验弹窗是否可见
      infoVisible: false, // 资讯校验弹窗是否可见
    };
  }

  componentDidMount() {
    const {
      globalM: {
        dataDictionary: { Bond_Type_PBC = [] },
      },
    } = this.props;
    this.setState({
      bondTypeList: this.changeTreeData(Bond_Type_PBC), // 债券类型下拉列表
    });
    // 查询持仓日期
    this.props.dispatch({
      type: 'bondInformationM/queryHoldDataList',
      payload: {},
      callback: (data) => {
        if (data) {
          const temp = [];
          data.map((item) => {
            temp.push({
              value: item,
              title: item,
            });
          });
          // 设置默认值为最新的持仓日期 其余下拉日期为历史日期
          this.AdvancedSearchRef?.props.form?.setFieldsValue({
            holdDate: data.length ? data[0] : undefined,
          });
          const obj = this.state.searchObj;
          obj.holdDate = data.length ? data[0] : undefined;
          this.setState(
            {
              holdDataList: [...temp],
              searchObj: { ...obj },
              latestholdDate: data.length ? data[0] : undefined, /// /保存最新的持仓
            },
            () => {
              this.getTableData();
            },
          );
        } else {
          this.setState({ holdDataList: [] });
        }
      },
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.tenant != this.props.tenant) {
      this.getTableData();
    }
  }

  // 债券分类树形
  changeTreeData = (arr) => {
    const tempArr = [];
    arr.forEach((item) => {
      tempArr.push({
        value: item.code,
        title: item.value,
        selectable: !item.children?.length,
        children: this.changeTreeData(item.children || []),
      });
    });
    return tempArr;
  };

  // 查询
  onQuery = (e) => {
    // 如果子查询还在 不可以点击查询按钮
    if (this.state.flag != '1') {
      message.warning(this.state.flag == 2 ? '请点击与资讯不一致提示语句，取消查询后重试！' : '请点击债券无评级提示语句，取消查询后重试！');
      return;
    }
    // 判断是历史数据还是当前数据
    if (this.AdvancedSearchRef) {
      if (this.state.latestholdDate != this.AdvancedSearchRef.props.form.getFieldValue('holdDate')) {
        this.setState({
          flag: '1', // 历史数据 永远查询全部
        });
      }
      this.setState({
        isHistory: this.state.latestholdDate != this.AdvancedSearchRef.props.form.getFieldValue('holdDate'),
      });
    }
    this.setState(
      {
        searchObj: e,
        currentPage: 1, // 页码
        numInPage: 10, // 一页展示数量
        isReset: false, // 是否点击重置
        selectedRowKeys: [], // 表格checkbox选择
        selectedRows: [], // 表格checkbox选择
        isBatchConfirmation: false, // 批量确认按钮置灰
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 重置
  onClear = () => {
    this.setState({
      isReset: true,
      filteredInfo: null, // 重置清除筛选条件
      bondType: undefined,
      originType: undefined,
    });

    // 重置日期
    this.AdvancedSearchRef?.props.form?.setFieldsValue({
      holdDate: this.state.latestholdDate,
    });
    // 租户也重置
    this.props.resetTenant();
  };

  // 表格分页切换
  handleTableChange = (pagination, filters) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      // 判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      this.setState({
        filteredInfo: { bondType: [], originType: [] },
        bondType: undefined,
        originType: undefined,
      });
      return;
    }
    this.setState(
      {
        currentPage: current,
        numInPage: pageSize,
        filteredInfo: filters,
        bondType: filters?.bondType?.length ? filters.bondType.join(',') : undefined,
        originType: filters?.originType?.length ? filters.originType.join(',') : undefined,
      },
      () => {
        this.getTableData();
      },
    );
  };

  // 获取表格数据
  getTableData = () => {
    const { currentPage, numInPage, searchObj, bondType, originType } = this.state;
    this.setState(
      {
        dataSource: undefined,
      },
      () => {
        this.props.dispatch({
          type: 'manbondInfoM/getDataList',
          payload: {
            ...searchObj,
            currentPage,
            numInPage,
            flag: this.state.flag,
            bondType,
            originType,
            tenant: this.props.tenant,
          },
          callback: (data) => {
            if (data?.dataSource?.length) {
              data.dataSource.map((item) => {
                item.originFlag = !(item.originType > 1);
              });
            }
            if (data)
              this.setState({
                dataSource: data.dataSource,
                count: data.count,
                noRateCount: data.noRateCount,
                addedThisMonth: data.addedThisMonth || 0,
                total: data.pageInfo?.total,
                currentPage: data.pageInfo?.currentPage,
                numInPage: data.pageInfo?.numInPage,
              });
            else {
              this.setState({
                dataSource: [],
                count: 0,
                noRateCount: 0,
                addedThisMonth: 0,
                total: 0,
                currentPage: 1,
                numInPage: 10,
              });
            }
          },
        });
      },
    );
  };

  // 新增/编辑弹窗
  addModalOpen = (type, record) => {
    this.setState(
      {
        pageType: type,
        visible: true,
      },
      () => {
        if (type == 'edit') {
          setTimeout(() => {
            const {
              form: { setFieldsValue },
            } = this.formGroupThis.props;
            this.setState({
              id: record.id,
              tradingCode: record.tradingCode,
            });
            this.formGroupThis.setSelect(`${record.securityExchange}-${record.tradingCode}`);
            setFieldsValue({
              securityExchange: record.securityExchange,
              bondType: record.bondType,
              bondRating: record.bondRating,
              issuer: record.issuer,
              supplementaryTool: record.supplementaryTool,
              issuerIndustry: record.issuerIndustry,
              issuerScale: record.issuerScale,
            });
          }, 0);
        }
      },
    );
  };

  // 批量确认
  confirm = () => {
    // 点击批量确认的时候，前端需要判断有几条数据待补充，并且做出提示
    if (this.state.selectedRows.filter((item) => item.isSuppleInfo == '1')?.length) {
      message.warning(`您有${this.state.selectedRows.filter((item) => item.isSuppleInfo == '1').length}条信息待补充`);
      return false;
    }
    this.props.dispatch({
      type: 'manbondInfoM/bondInfoListConfirm',
      payload: { data: this.state.selectedRowKeys },
      callback: (res) => {
        if (res) {
          message.success('批量确认成功！');
          this.setState(
            {
              selectedRowKeys: [],
              selectedRows: [],
              isBatchConfirmation: false,
            },
            () => {
              this.getTableData();
            },
          );
        }
      },
    });
  };

  // 列表点击响应
  onSelectChange = (selectedRowKeys, selectedRows) => {
    const isBatchConfirmation = selectedRowKeys.length > 0;
    this.setState({
      selectedRowKeys,
      selectedRows,
      isBatchConfirmation,
    });
  };

  // 删除onDelete
  onDelete = (id) => {
    this.props.dispatch({
      type: 'manbondInfoM/deleteById',
      payload: { id },
      callback: () => {
        message.success('删除成功!');
        // 删除成功 刷新列表
        this.getTableData();
      },
    });
  };

  // 改变columns的样式
  changeColumns = (columns) => {
    const {
      globalM: {
        dataDictionary: { Bond_Type_PBC = [], GJTJJHYFLI = [], SUPPLEMENTARY_TOOL_DICT = [], ISSUER_BY_SIZE = [], ORIGIN_TYPE_DICT = [] },
      },
    } = this.props;
    let { filteredInfo } = this.state;
    const bondArr = _.cloneDeep(Bond_Type_PBC.filter((item) => item.code != '811275'));
    filteredInfo = filteredInfo || {};
    const data = columns;
    if (data && data.length) {
      if (data[data.length - 1].title !== '操作' && !this.state.isHistory) {
        data.push({
          dataIndex: 'operate',
          key: 'operate',
          type: 'operate',
          title: '操作',
          operates: [
            {
              title: '编辑',
              onClick: (record) => {
                this.addModalOpen('edit', record);
              },
            },
            {
              title: '删除',
              onClick: (record) => {
                this.onDelete(record.id);
              },
              rules: {
                disabled: { relation: 'or', items: [{ key: 'originFlag', value: [true], relation: ['='] }] },
              },
            },
          ],
        });
      }
      data.map((item) => {
        if (item.key == 'securityExchange') {
          item.render = (text, record) => {
            let temp = '--';
            config.map((item) => {
              if (item.value == text) {
                temp = item.title;
              }
            });
            return temp;
          };
        }
        if (item.key == 'bondType') {
          item.type = 'filterCol';
          (item.filters = bondArr.map((item) => {
            return { text: item.value, value: item.code };
          })),
            (item.filterMultiple = true);
          (item.filteredValue = filteredInfo.bondType || null),
            (item.render = (text, record) => {
              let temp = '--';
              this.state.bondTypeList.map((item) => {
                if (item.value == text) {
                  temp = item.title;
                } else if (item.children && item.children.length) {
                  item.children.map((childItem) => {
                    if (childItem.value == text) {
                      temp = childItem.title;
                    }
                  });
                }
              });
              return temp;
            });
        }
        // 来源
        if (item.key == 'originType') {
          item.type = 'filterCol';
          (item.filters = ORIGIN_TYPE_DICT.map((item) => {
            return { text: item.value, value: item.code };
          })),
            (item.filterMultiple = true);
          (item.filteredValue = filteredInfo.originType || null),
            (item.render = (text, record) => {
              return findValueByCode(text, ORIGIN_TYPE_DICT);
            });
        }
        if (item.key == 'issuerScale') {
          item.render = (text, record) => {
            let temp = '--';
            ISSUER_BY_SIZE.map((item) => {
              if (item.code == text) {
                temp = item.value;
              }
            });
            return temp;
          };
        }
        if (item.key == 'supplementaryTool') {
          item.render = (text, record) => {
            let temp = '--';
            SUPPLEMENTARY_TOOL_DICT.map((item) => {
              if (item.code == text) {
                temp = item.value;
              }
            });
            return temp;
          };
        }
        if (item.key == 'issuerIndustry') {
          item.render = (text, record) => {
            let temp = '--';
            GJTJJHYFLI.map((item) => {
              if (item.code == text) {
                temp = item.value;
              }
            });
            return temp;
          };
        }
        if (item.key == 'bondRating') {
          item.render = (text, record) => {
            if (text == 'NOT_RATED') {
              text = '无评级';
            }
            return text || '--';
          };
        }
      });
    }
    return data;
  };

  // 新增/编辑
  handleOk = () => {
    const {
      form: { validateFields, resetFields },
    } = this.formGroupThis.props;
    const { dispatch } = this.props;
    validateFields((err, fieldsValue) => {
      if (err) return;
      const value = {
        tradingCode: this.state.tradingCode,
        securityExchange: fieldsValue.securityExchange,
        bondType: fieldsValue.bondType,
        bondRating: fieldsValue.bondRating,
        issuer: fieldsValue.issuer,
        supplementaryTool: fieldsValue.supplementaryTool,
        issuerIndustry: fieldsValue.issuerIndustry,
        issuerScale: fieldsValue.issuerScale,
        id: this.state.id,
      };
      dispatch({
        type: 'manbondInfoM/bondInfoListAdd',
        payload: value,
        callback: (res) => {
          if (res) {
            this.getTableData();
            // eslint-disable-next-line max-lines
            this.setState({
              visible: false,
              tradingCode: '',
              id: undefined,
            });
            resetFields();
          }
        },
      });
    });
  };

  // 关闭页面 清空表单
  onCancel = () => {
    const {
      form: { validateFields, resetFields },
    } = this.formGroupThis.props;
    this.setState({ visible: false }, () => {
      setTimeout(() => {
        resetFields();
      }, 300);
    });
  };

  // 新建根据证券代码回填
  tradingCodeChange = (e) => {
    if (this.state.pageType == 'edit') return;
    if (e) {
      if (e.tradingCode) {
        const {
          form: { setFieldsValue },
        } = this.formGroupThis.props;
        this.setState({
          tradingCode: e?.tradingCode,
        });
        this.props.dispatch({
          type: 'manbondInfoM/bondInfoDetail',
          payload: {
            tradingCode: e.tradingCode,
            exchangeCode: e.exchangeCode,
          },
          callback: (data) => {
            setFieldsValue({
              securityExchange: data.exchangecode,
              bondType: data.bondType,
              bondRating: data.bondRating,
              supplementaryTool: data.supplementaryTool,
              issuerIndustry: data.issuerIndustry,
              issuerScale: data.issuerScale,
            });
          },
        });
      } else {
        this.setState({
          tradingCode: e,
        });
      }
    }
  };

  // 模态框
  showModal = () => {
    const { bondTypeList, pageType, visible } = this.state;
    const {
      loading,
      globalM: {
        dataDictionary: { SMART_BETA_RATING = [], SUPPLEMENTARY_TOOL_DICT = [], ISSUER_BY_SIZE = [] },
      },
    } = this.props;
    const modalProps = {
      visible,
      onOk: this.handleOk,
      onCancel: () => {
        this.onCancel();
      },
      title: pageType == 'edit' ? '编辑' : '新增',
      destroyOnClose: false,
      confirmLoading: loading.effects['manbondInfoM/bondInfoListAdd'] === true || loading.effects['manbondInfoM/bondInfoDetail'] === true,
      width: 960,
      maskClosable: false,
    };
    return (
      <ModalC {...modalProps}>
        <FormGroup
          widthSet={1000}
          dataSource={[
            {
              dataIndex: 'tradingCode',
              title: '证券代码',
              type: DATA_ENTRY.SECURITIESCODE,
              initialValue: '',
              disabled: pageType == 'edit',
              rules: [{ required: true, message: '请输入证券代码' }],
              onChange: (e) => this.tradingCodeChange(e),
              codeType: codeType.allZq,
              isInput: true,
              span: 12,
              positionBody: true,
              onRef: (ref) => (this.formGroupThis = ref),
            },
            {
              dataIndex: 'securityExchange',
              title: '交易市场',
              type: DATA_ENTRY.TRADINGMARKET,
              marketType: ['jys', 'yhj'],
              disabled: pageType == 'edit',
              rules: [{ required: true, message: '请选择交易市场' }],
              span: 12,
            },
            {
              dataIndex: 'bondType',
              title: '债券类型',
              type: DATA_ENTRY.TREESELECT,
              dataSource: bondTypeList,
              treeDefaultExpandAll: true,
              positionBody: true,
              allowClear: true,
              rules: [{ required: true, message: '请选择债券类型' }],
              span: 12,
            },
            {
              dataIndex: 'bondRating',
              title: '债项评级',
              type: DATA_ENTRY.SELECT,
              positionBody: true,
              allowClear: true,
              dataSource: SMART_BETA_RATING.map((item) => {
                const obj = {
                  title: item.value,
                  value: item.code,
                };
                return obj;
              }),
              rules: [{ required: true, message: '请选择债项评级' }],
              span: 12,
            },
            {
              dataIndex: 'supplementaryTool',
              type: DATA_ENTRY.SELECT,
              positionBody: true,
              title: '补充工具',
              dataSource: SUPPLEMENTARY_TOOL_DICT.map((item) => {
                const obj = {
                  title: item.value,
                  value: item.code,
                };
                return obj;
              }),
              span: 12,
            },
            {
              dataIndex: 'issuerIndustry',
              title: '发行机构所属行业',
              type: DATA_ENTRY.FUNDAPPLICATIONINDUSTRYC,
              OnlySupportFirstLevel: true,
              parentCanClick: true,
              positionBody: true,
              rules: [{ required: true, message: '请选择发行机构所属行业' }],
              span: 12,
            },
            {
              dataIndex: 'issuerScale',
              title: '发行机构类型（按规模划分）',
              type: DATA_ENTRY.SELECT,
              dataSource: ISSUER_BY_SIZE.map((item) => {
                const obj = {
                  title: item.value,
                  value: item.code,
                };
                return obj;
              }),
              disabled: false,
              span: 12,
              positionBody: true,
              rules: [{ required: true, message: '请选择发行机构类型（按规模划分）!' }],
            },
          ]}
          autoLayout={false}
        />
      </ModalC>
    );
  };

  // 点击了提示语
  tipClick = (type, flag) => {
    this.setState(
      {
        flag: flag == true ? (type == 'noRate' ? '3' : '2') : '1',
      },
      () => {
        this.setState(
          {
            isReset: false, // 是否点击重置
            selectedRowKeys: [], // 表格checkbox选择
            selectedRows: [], // 表格checkbox选择
            isBatchConfirmation: false, // 批量确认按钮置灰
            currentPage: 1,
          },
          () => {
            this.getTableData();
          },
        );
      },
    );
  };

  // 同发行人校验
  onVerify = () => {
    this.setState({
      issuerVisible: true,
    });
  };

  // 资讯校验
  onVerifyInfo = () => {
    this.setState({
      infoVisible: true,
    });
  };

  render() {
    const { originType, bondType, bondTypeList, searchObj, columns, noRateCount, dataSource, currentPage, total, numInPage, selectedRowKeys, isBatchConfirmation, count } =
      this.state;
    const { loading } = this.props;
    const dataSourceQuery = [
      {
        dataIndex: 'codeName',
        title: '代码或名称',
        type: DATA_ENTRY.INPUT,
        allowClear: true,
      },
      {
        dataIndex: 'isConfirm',
        title: '是否已确认',
        isTrueFalseJudge: true,
        type: DATA_ENTRY.SELECT,
        allowClear: true,
      },
      {
        dataIndex: 'holdDate',
        title: '持仓日期',
        type: DATA_ENTRY.SELECT,
        allowClear: false,
        dataSource: this.state.holdDataList || [],
      },
      {
        dataIndex: 'issuer',
        title: '发行人',
        type: DATA_ENTRY.INPUT,
        allowClear: true,
      },
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      getCheckboxProps: (record) => {
        if (record.isSuppleInfo == '1' || record.isConfirm == '1') {
          return { disabled: true };
        } else {
          return null;
        }
      },
    };
    const newColumns = this.changeColumns(_.cloneDeep(columns));
    return (
      <div>
        <AdvancedSearch onRef={(ref) => (this.AdvancedSearchRef = ref)} dataSource={dataSourceQuery} onQuery={this.onQuery} onClear={this.onClear} />
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '20px' }}>
          <div style={{ display: 'flex', alignContent: 'center' }}>
            {!this.state.isHistory && (
              <div>
                <PrimaryC title='新增' onClick={() => this.addModalOpen('add')} />
              </div>
            )}
            {!this.state.isHistory && (
              <div style={{ marginLeft: '16px', marginRight: '16px' }}>
                <PrimaryC title='批量确认' onClick={this.confirm} disabled={!isBatchConfirmation} />
              </div>
            )}
            <div style={{ marginRight: '20px' }}>
              <ExportC
                url={'gateway/instrument-server/bndRegulation/bndExport'}
                search={{ ...searchObj, flag: this.state.flag, tenant: this.props.tenant, originType: originType ?? '', bondType: bondType ?? '' }}
                disabled={!dataSource?.length}
              />
            </div>
            <div style={{ marginRight: '20px' }}>{!this.state.isHistory && <PrimaryGhostC title='同发行人校验' onClick={this.onVerify} />}</div>
            <div style={{ marginRight: '20px' }}>{!this.state.isHistory && <PrimaryGhostC title='资讯对比校验' onClick={this.onVerifyInfo} />}</div>

            {!this.state.isHistory && (
              <div style={{ display: 'flex', paddingLeft: '15px' }}>
                <TipsInfo
                  count={noRateCount}
                  type='bond'
                  disabledFlag={this.state.flag}
                  handleClick={(e) => {
                    this.tipClick('noRate', e);
                  }}
                />
              </div>
            )}
          </div>
          {!this.state.isHistory && (
            <div style={{ display: 'flex' }}>
              <RightInfo redTitle={`本月新增标的${this.state.addedThisMonth || 0}只`} />
            </div>
          )}
        </div>
        <div style={{ marginTop: '16px' }}>
          <TableC
            columns={newColumns}
            dataSource={dataSource}
            current={currentPage}
            total={total}
            pageSize={numInPage}
            rowKey='id'
            loading={loading.effects['manbondInfoM/getDataList']}
            scroll={{ x: 'max-content' }}
            onChange={this.handleTableChange}
            rowSelection={!this.state.isHistory ? rowSelection : undefined}
            rowClassName={(record) => {
              return record.createTs == this.state.latestholdDate ? myStyle.redCls : '';
            }}
          />
          <div style={{ position: 'absolute', bottom: '16px', left: '0px', display: 'flex' }}></div>
        </div>
        <div>{this.showModal()}</div>
        {this.state.issuerVisible ? (
          <IssuerModal visible={this.state.issuerVisible} changeVisible={(e) => this.setState({ issuerVisible: e })} bondTypeList={bondTypeList} holdDate={searchObj?.holdDate} />
        ) : null}
        {this.state.infoVisible ? (
          <InfoModal
            visible={this.state.infoVisible}
            changeVisible={(e) => this.setState({ infoVisible: e })}
            // tenant = { this.props.tenant}
          />
        ) : null}
      </div>
    );
  }
}
export default connect(({ manbondInfoM, globalM, loading }) => ({ manbondInfoM, globalM, loading }))(BondInfo);
